package com.complaint.rest;

import com.complaint.rest.dao.UserDAO;
import com.complaint.rest.dao.UserDAOImpl;
import com.complaint.rest.model.User;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * Created by Alex
 */
@Path("/user")
public class UserService {
    private static UserDAO userDAO = new UserDAOImpl();

    @POST
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response createUser(User user) {
        if (user.getId() == null || (user.getId() != null && user.getId().isEmpty())) {
            User persistedUser = userDAO.addUser(user);
            return Response.ok(persistedUser).build();
        } else {
            userDAO.updateUser(user);
            return Response.ok(user).build();
        }
    }

    @DELETE
    @Path("/{id}")
    public Response deleteUser(@PathParam("id") String id) {
        userDAO.removeUser(userDAO.getUser(id));
        return Response.noContent().build();
    }

    @GET
    @Path("/{id}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response getUser(@PathParam("id") String id) {
        User user = userDAO.getUser(id);
        return Response.ok(user).build();
    }

    @GET
    @Path("/email/{email}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Response getUserByEmail(@PathParam("email") String email) {
        User user = userDAO.getUserByEmail(email);
        return user != null ? Response.ok(user).build() : Response.noContent().build();
    }
}